<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>工程概预算设计管理</title>
    <!-- 引入Layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        body {
            background-color: #f2f2f2;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .login-container {
            width: 380px;
            padding: 30px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            border: 1px solid #ddd;
            border-top: 1px solid #eee;
            border-left: 1px solid #eee;
            position: relative;
        }

        .login-container::before {
            content: "";
            position: absolute;
            top: -5px;
            left: -5px;
            right: -5px;
            bottom: -5px;
            border-radius: 8px;
            background: linear-gradient(145deg, #ffffff, #e6e6e6);
            z-index: -1;
            box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.1);
        }

        .login-title {
            text-align: center;
            margin-bottom: 30px;
            font-size: 22px;
            color: #333;
        }

        .layui-form-item {
            margin-bottom: 20px;
        }

        .layui-input {
            height: 40px;
            line-height: 40px;
        }

        .login-btn {
            width: 50%;
            height: 40px;
        }
    </style>
</head>

<body>
    <div class="login-container">
        <h2 class="login-title">系统登录</h2>
        <form class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">账 号</label>
                <div class="layui-input-block">
                    <input type="text" name="user_id" required lay-verify="required" placeholder="请输入账号"
                        autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密 码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                        autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="text-align: center;padding-top: 15px;">
                <button type="submit" class="layui-btn login-btn" lay-submit lay-filter="login">登录</button>
            </div>
        </form>
    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/js/auth-utils.js"></script>
    <script src="/layui/layui.js"></script>
    <script>
        // 页面加载时立即执行历史记录替换
        (function () {
            // 清除所有历史记录并替换当前页面
            if (window.history && window.history.replaceState) {
                window.history.replaceState({ isLoginPage: true }, null, window.location.href);
                window.history.pushState({ isLoginPage: true }, null, window.location.href);
            }
        })();

        // 监听popstate事件（浏览器后退/前进按钮）
        window.addEventListener('popstate', function (event) {
            if (event.state && event.state.isLoginPage) {
                if (window.history && window.history.replaceState) {
                    // 立即替换当前状态，阻止后退
                    window.history.replaceState({ isLoginPage: true }, null, window.location.href);

                    // 再次添加新的历史记录条目
                    setTimeout(function () {
                        window.history.pushState({ isLoginPage: true }, null, window.location.href);
                    }, 100);
                }
            }
        });

        function validateToken(token) {
            return new Promise((resolve, reject) => {
                if (!token) {
                    resolve(false);
                    return;
                }

                try {
                    // 1. 先检查token格式是否正确
                    const parts = token.split('.');
                    if (parts.length !== 3) {
                        resolve(false);
                        return;
                    }

                    // 2. 检查token是否过期（前端初步检查）
                    const payload = JSON.parse(atob(parts[1]));
                    const isExpired = payload.exp * 1000 < Date.now();

                    if (isExpired) {
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        resolve(false);
                        return;
                    }

                    // 3. 发送到服务器进行完整验证
                    http.get(API_CONFIG.ENDPOINTS.VALIDATE_TOKEN, {
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    })
                        .then(response => {
                            if (response.valid) {
                                resolve(true);
                            } else {
                                // token无效，清除本地存储
                                localStorage.removeItem('token');
                                localStorage.removeItem('user');
                                resolve(false);
                            }
                        })
                        .catch(error => {
                            console.error('Token验证失败:', error);
                            resolve(false);
                        });

                } catch (error) {
                    console.error('Token解析失败:', error);
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    resolve(false);
                }
            });
        }

        layui.use(['form', 'layer'], function () {
            var form = layui.form;
            var layer = layui.layer;

            // 页面加载时检查是否已登录，如果已登录则跳转到主页面
            if (localStorage.getItem('token')) {
                var loadingIndex = layer.load(1);

                // 确保 authUtils 已加载
                if (typeof window.authUtils !== 'undefined' && window.authUtils.validateToken) {
                    window.authUtils.validateToken(localStorage.getItem('token'))
                        .then(valid => {
                            layer.close(loadingIndex);
                            if (valid) {
                                const user = window.authUtils.getCurrentUser();
                                if (user) {
                                    window.authUtils.checkUserRoleAndRedirect(user);
                                } else {
                                    window.location.replace('/main');
                                }
                            }
                        })
                        .catch(error => {
                            layer.close(loadingIndex);
                            console.error('Token验证错误:', error);
                        });
                } else {
                    layer.close(loadingIndex);
                    console.error('authUtils 未正确加载');
                }
            }

            form.on('submit(login)', function (data) {
                var loading = layer.load(1);
                http.post(API_CONFIG.ENDPOINTS.LOGIN, data.field)
                    .then(function (res) {
                        if (!res.data.token) {
                            throw new Error('未获取到Token');
                        }

                        localStorage.setItem('token', res.data.token);
                        if (res.data.user) {
                            localStorage.setItem('user', JSON.stringify(res.data.user));
                        }
                        if (res.data.session) {
                            localStorage.setItem('session', JSON.stringify(res.data.session));
                        }

                        layer.close(loading);
                        layer.msg(res.msg || '登录成功，欢迎使用！', {
                            icon: 1,
                            time: 1500
                        }, function () {
                            //window.location.replace('/main');
                            window.authUtils.checkUserRoleAndRedirect(res.data.user);
                        });
                    })
                    .catch(function (err) {
                        layer.close(loading);

                        // 更详细的错误信息显示
                        let errorMsg = '登录失败';
                        if (err.msg) {
                            errorMsg = err.msg;
                        } else if (err.message) {
                            errorMsg = err.message;
                        }

                        layer.msg(errorMsg, { icon: 2, time: 3000 });
                    });
                return false;
            });
        });   
    </script>
</body>

</html>